import { defineStore } from "pinia";
import { ref } from "vue";
import { userManageApi } from "@/api/user/userManage";
import { message } from "ant-design-vue";
import type { User, UserForm, UserListParams } from "@/types/user";

export const useUserManageStore = defineStore("userManage", () => {
  // 用户列表数据
  const userList = ref<User[]>([]);
  
  // 分页信息
  const currentPage = ref(1);
  const pageSize = ref(2);
  const total = ref(0);
  
  // 加载状态
  const loading = ref(false);

  /**
   * 获取用户列表
   */
  async function fetchUserList(params: UserListParams) {
    loading.value = true;
    try {
      const res = await userManageApi.getUserList(params);
      if (res.code === 0) {
        userList.value = res.data.records || [];
        total.value = res.data.total || 0;
        currentPage.value = params.current;
        pageSize.value = params.pageSize;
      } else {
        message.error(res.message || "获取用户列表失败");
      }
    } catch (error) {
      message.error("获取用户列表失败");
      console.error("获取用户列表错误:", error);
    } finally {
      loading.value = false;
    }
  }

  /**
   * 添加用户
   */
  async function addUser(userData: UserForm) {
    try {
      const res = await userManageApi.addUser(userData);
      if (res.code === 0) {
        return res.data;
      } else {
        message.error(res.message || "添加用户失败");
        throw new Error(res.message);
      }
    } catch (error) {
      message.error("添加用户失败");
      throw error;
    }
  }

  /**
   * 更新用户
   */
  async function updateUser(userId: number, userData: UserForm) {
    try {
      const res = await userManageApi.updateUser(userId, userData);
      if (res.code === 0) {
        return res.data;
      } else {
        message.error(res.message || "更新用户失败");
        throw new Error(res.message);
      }
    } catch (error) {
      message.error("更新用户失败");
      throw error;
    }
  }

  /**
   * 删除用户
   */
  async function deleteUser(userId: number) {
    try {
      const res = await userManageApi.deleteUser(userId);
      if (res.code === 0) {
        return res.data;
      } else {
        message.error(res.message || "删除用户失败");
        throw new Error(res.message);
      }
    } catch (error) {
      message.error("删除用户失败");
      throw error;
    }
  }
  return {
    userList,
    currentPage,
    pageSize,
    total,
    loading,
    fetchUserList,
    addUser,
    updateUser,
    deleteUser
  };
});